﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;

namespace LD
{

    public class HiveFunction
    {
        public readonly static HiveFunction intc = new HiveFunction();
        private HttpClientHelper hch = new HttpClientHelper();
        public static HiveFunction instance
        {
            get { return intc; }
        }

        private string hiveUpFailDir = @"D:\Hive\hiveUpFail\";  //初次上传失败保存地址

        string upFailHiveLog = @"D:\Hive\ReSendHiveLog\"; // 重复上传 log 记录
        string hiveInfoError = @"D:\Hive\hiveError\";        // hive信息错误记录，信息错误，或者超时，
        string directorypath = "D:\\Hive\\BZTemp_RetryFail\\";  // hive 重复上传保存log 位置。


        private void SaveUpLog(string strs)
        {
            try
            {

                string upHiveLog = upFailHiveLog + DateTime.Now.ToString("yyyyMMdd") + "\\";
                if (!Directory.Exists(upHiveLog))
                {
                    Directory.CreateDirectory(upHiveLog);
                }
                File.AppendAllText(upHiveLog + DateTime.Now.ToString("yyyyMMdd") + ".txt", DateTime.Now.ToString("HH:mm:ss") + ":" + strs + "\r\n", Encoding.Default);

            }
            catch
            {

            }
        }
        public string[] GetFilepathsFromhivedata(string hivedata)
        {
            string blobsdata = hivedata.Substring(hivedata.IndexOf("\"blobs\":"));
            string[] files = blobsdata.Replace("\"blobs\":[", "").Replace("]", "").Replace("\"", "").Replace("{", "").Replace("}", "").Split(',');
            string[] filepaths = new string[files.Length];
            for (int i = 0; i < filepaths.Length; i++)
            {
                filepaths[i] = files[i].Replace("file_name:", "");
            }
            return filepaths;
        }

        public bool ReSendMachineData(string cmd, out int indx)
        {
            string str2 = "";
            indx = 0;
            string requestUriString = "http://10.0.0.2:5008/v5/capture/machinedata";
            try
            {
                str2 = hch.PostMoths_form(requestUriString, cmd);
            }
            catch (Exception e)
            {
                str2 = e.ToString();
            }
            try
            {
                DateTime dt = DateTime.Now;
                if (!Directory.Exists(directorypath))
                {
                    Directory.CreateDirectory(directorypath);
                }
                string fileName = dt.ToString("yyyy-MM-dd") + ".txt";
                string filepath = directorypath + fileName;
                if (!File.Exists(filepath))
                {
                    File.Create(filepath).Close();
                }
                FileStream fs = new FileStream(filepath, FileMode.Append, FileAccess.Write);
                StreamWriter sw = new StreamWriter(fs, Encoding.Default);
                sw.WriteLine(dt.ToString("yyyy-MM-dd") + "   " + dt.ToString("HH:mm:ss") + "   " + "发送的数据为：" + requestUriString + " " + cmd);
                sw.WriteLine(dt.ToString("yyyy-MM-dd") + "   " + dt.ToString("HH:mm:ss") + "   " + "接收到返回的数据为：" + str2);
                sw.Flush();
                sw.Close();
                fs.Close();
                if (str2.Contains("Success machinedata logged"))
                {
                    SaveUpLog("上传成功");
                    return true;
                }
                else if (str2.Contains("4"))
                {
                    SaveUpLog("重复上传" + str2);
                    indx = 1;
                    return true;
                }
                else
                {
                    SaveUpLog("失败！");
                }
            }
            catch (Exception e)
            {
                SaveUpLog("失败！" + e.ToString());
            }
            return false;
        }

        #region
        public void SendMachineData(string SN,
                                    string TestResult,
                                    DateTime starttime,
                                    DateTime endtime,
                                    List<string> TestDatas,
                                    double CT,
                                    string Ver,
                                    List<string> path,
                                    List<double> coax,
                                    Action<string> act = null)
        {
            string str2 = "";
            string cmd = "";
            ThreadPool.QueueUserWorkItem(new WaitCallback((o) =>
            {
                List<string> TestNames = new List<string>()
            {
                "A1_Tor", "A2_Tor",  "B1_Tor", "B2_Tor",
                "A1_Deg", "A2_Deg", "B1_Deg", "B2_Deg"
            };
                List<(double, double)> limit = new List<(double, double)>()
            {
                (2.45, 2.55), (2.45, 2.55), (2.45, 2.55), (2.45, 2.55),
                (5300, 10800), (5300, 10800), (5300, 10800), (5300, 10800)
            };
                List<string> coaxNames = new List<string>()
            {
                "CoaxA1" , "CoaxA2" ,"CoaxB1" ,"CoaxB2"
            };
                string data = "";
                string lim = "";
                string Coax = "";
                for (int i = 0; i < TestNames.Count; i++)
                {
                    if (i != TestNames.Count - 1)
                    {
                        data += (TestNames[i] + "\":" + TestDatas[i] + ",\"");
                        lim += ("\"" + TestNames[i] + "\":{\"upper_limit\":" + limit[i].Item2 + ",\"lower_limit\":" + limit[i].Item1 + "},");

                    }
                    else
                    {
                        data += (TestNames[i] + "\":" + TestDatas[i] + ",");
                        lim += ("\"" + TestNames[i] + "\":{\"upper_limit\":" + limit[i].Item2 + ",\"lower_limit\":" + limit[i].Item1 + "}},");
                    }

                }
                for (int i = 0; i < coaxNames.Count; i++)
                {
                    if (i != coaxNames.Count - 1)
                    {
                        Coax += (coaxNames[i] + "\":" + coax[i] + ",\"");


                    }
                    else
                    {
                        Coax += (coaxNames[i] + "\":" + coax[i] + ",");
                    }
                }
                string pat = "";
                for (int i = 0; i < path.Count; i++)
                {
                    if (i != path.Count - 1)
                    {
                        pat += ("{\"file_name\":\"" + path[i] + "\"}" + ",");
                    }
                    else
                    {
                        pat += ("{\"file_name\":\"" + path[i] + "\"}");
                    }
                }
                try
                {

                    cmd = "{\"unit_sn\":\"" + SN +
                          "\",\"serials\":{" + "\"TOP_CASE\":\"" + SN + "\",\"SYSTEMSN\":\"" + SN + "\"},\"pass\":\""
                          + TestResult + "\",\"input_time\":\"" +
                          starttime.ToString("yyyy-MM-dd") + "T" + starttime.ToString("HH:mm:ss.f2") + "+0800\",\"output_time\":\"" +
                          endtime.ToString("yyyy-MM-dd") + "T" + endtime.ToString("HH:mm:ss.f2") + "+0800\",\"data\":{\""
                          + data + "\"" + Coax
                          + "\"CT\"" + ":" + CT +
                          "}," +
                          "\"limit\":{" +
                          lim +
                          "\"attr\":{" +
                          "\"sw_version\":\"" + Ver +
                          "\"},\"blobs\":["
                          + pat
                          + "]}";
                }
                catch
                {
                }
                if (!String.IsNullOrEmpty(SN) && SN.Length >= 10)
                {
                    try
                    {
                        //Globals.LOGPATH = "D:\\Data\\Log\\hivelog\\" + DateTime.Now.ToString("yyyyMMdd") + ".txt";
                        //string requestUriString = "http://10.0.0.2:5008/v5/capture/machinedata";
                        //str2 = hch.PostMoths_form(requestUriString, cmd);
                        //string timeStamp = DateTime.Now.ToString("yy-MM-dd HH:mm:ss-ff:");
                        //Log.Save(timeStamp + cmd + "\r\n", Globals.LOGPATH, ELog.Append);
                        //Log.Save(timeStamp + str2 + "\r\n", Globals.LOGPATH, ELog.Append);
                        //act?.Invoke(cmd + "\r\n" + str2 + "\r\n");
                    }
                    catch (Exception e)
                    {
                        str2 = e.ToString();
                    }
                }
            }));
        }
        #endregion


        public void SendMachineData(string SN, string cmd)
        {
            string str2 = "";
            string surl = "";
            if (!String.IsNullOrEmpty(SN) && SN.Length > 10)
            {
                try
                {
                    string requestUriString = "http://10.0.0.2:5008/v5/capture/machinedata";
                    str2 = hch.PostMoths_form(requestUriString, cmd);
                }
                catch (Exception e)
                {
                    str2 = e.ToString();
                }
            }
            try
            {
                DateTime dt = DateTime.Now;
                string directorypath = "D:\\Hive\\BZTemp\\";
                if (!Directory.Exists(directorypath))
                {
                    Directory.CreateDirectory(directorypath);
                }
                string fileName = dt.ToString("yyyy-MM-dd") + ".txt";
                string filepath = directorypath + fileName;
                if (!File.Exists(filepath))
                {
                    File.Create(filepath).Close();
                }
                FileStream fs = new FileStream(filepath, FileMode.Append, FileAccess.Write);
                StreamWriter sw = new StreamWriter(fs, Encoding.Default);
                sw.WriteLine(dt.ToString("yyyy-MM-dd") + "   " + dt.ToString("HH:mm:ss") + "   " + "发送的数据为：" + surl + " " + cmd);
                sw.WriteLine(dt.ToString("yyyy-MM-dd") + "   " + dt.ToString("HH:mm:ss") + "   " + "接收到返回的数据为：" + str2);

                sw.Flush();
                sw.Close();
                fs.Close();
                if (str2.Contains("Success machinedata logged"))
                {
                }
                else
                {
                    if (str2.Contains("4"))
                    {
                        string path = hiveInfoError;
                        if (!Directory.Exists(path))
                        { Directory.CreateDirectory(path); }
                        File.WriteAllText(path + "\\" + SN + ".txt", cmd, Encoding.Default);
                    }
                    else
                    {
                        string path = hiveUpFailDir;
                        if (!Directory.Exists(path))
                        { Directory.CreateDirectory(path); }
                        File.WriteAllText(path + "\\" + SN + ".txt", cmd, Encoding.Default);
                    }

                }
            }
            catch
            {
                //UpdateInfo("异常信息保存失败！", 1);
            }

        }
        public bool SendHiveString(string SN, string titleName, string title, DateTime startTime, DateTime endTime,
                             string dataName, string data, List<string> upper_limit,
                        List<string> lower_limit, List<string> Path, string Sw_Version)
        {
            string cmd = "";
            string cmdtitle = "";
            string cmddatas = "";
            string cmddatasLimit = "";
            string cmdPath = "";
            try
            {
                //显示SN，时间。
                #region
                string[] titleNames = titleName.Trim().Split(','); //title 名称
                string[] titles = title.Trim().Split(',');         // title 内容

                for (int i = 0; i < titleNames.Length; i++)
                {
                    { cmdtitle += "\"" + titleNames[i] + "\"" + ":" + "\"" + titles[i] + "\"" + ","; }

                }
                cmdtitle += "\"input_time\"" + ":" + "\"" + startTime.ToString("yyyy-MM-dd") + "T" + startTime.ToString("HH:mm:ss.f2") + "+0800" + "\"" + "," +
                           "\"output_time\"" + ":" + "\"" + endTime.ToString("yyyy-MM-dd") + "T" + endTime.ToString("HH:mm:ss.f2") + "+0800" + "\"";
                #endregion
                //显示数据，和Spec
                #region
                string[] dataNames = dataName.Trim().Split(',');
                string[] datas = data.Trim().Split(',');

                for (int i = 0; i < dataNames.Length; i++)
                {
                    if (i == dataNames.Length - 1)
                        cmddatas += "\"" + dataNames[i] + "\"" + ":" + datas[i];
                    else
                        cmddatas += "\"" + dataNames[i] + "\"" + ":" + datas[i] + ",";
                }
                for (int i = 0; i < dataNames.Length; i++)
                {
                    if (i == dataNames.Length - 1)
                    {
                        cmddatasLimit += "\"" + dataNames[i] + "\":{"
                                               + "\"upper_limit\"" + ":" + upper_limit[i] + ","
                                               + "\"lower_limit\"" + ":" + lower_limit[i] +
                                              "}";
                    }
                    else
                    {
                        cmddatasLimit += "\"" + dataNames[i] + "\":{"
                                               + "\"upper_limit\"" + ":" + upper_limit[i] + ","
                                               + "\"lower_limit\"" + ":" + lower_limit[i] +
                                               "}" + ",";
                    }

                }
                #endregion

                //显示csv和图片
                for (int i = 0; i < Path.Count; i++)
                {
                    if (i == Path.Count - 1)
                    {
                        cmdPath += "{" + "\"file_name\"" + ":" + "\"" + Path[i] + "\"" + "}";
                    }
                    else
                    {
                        cmdPath += "{" + "\"file_name\"" + ":" + "\"" + Path[i] + "\"" + "}" + ",";
                    }
                }
                cmd = "{" +
                        cmdtitle + "," +
                    "\"data\":{" + cmddatas + "}," +
                    "\"limit\":{" + cmddatasLimit + "}," +
                    "\"attr\":{" + "\"Sw_Version\":" + "\"" + Sw_Version + "\"}," +
                    "\"blobs\":[" + cmdPath + "]" + "}";

                SendMachineData(SN, cmd);
                return true;
            }
            catch (Exception e)
            {
                SaveUpLog(e.ToString());
                return false;

            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="state">机台状态：[1:工作][2：空闲][3：工程师模式][4：暂停][5：故障](需为字符)</param>
        public void SendMachineState(string state)
        {
            string cmd = "";

            if (state != "5")
            {
                cmd = "{\"publisher_id\":\"086deb0a-c401-46fd-8137-19c2c3f2b57d\"," + "\"machine_state\":" +
                                 state + ",\"state_change_time\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "T" +
                                 DateTime.Now.ToString("HH:mm:ss.f2") + "+0800\",\"data\":{}}";
            }
            else
            {
                cmd = "{\"publisher_id\":\"086deb0a-c401-46fd-8137-19c2c3f2b57d\"," + "\"machine_state\":" +
                                 state + ",\"state_change_time\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "T" +
                                 DateTime.Now.ToString("HH:mm:ss.f2") + "+0800\",\"data\":{\"message\":\"Stoptrigger\"," + "\"code\":\"-1001\"}}";
            }

            string str = "";
            string str2 = "";
            try
            {
                string requestUriString = "http://10.0.0.2:5008/v5/capture/machinestate";
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUriString);
                request.Timeout = 100;
                request.Method = "POST";
                request.ContentType = "application/json;";
                request.Proxy = null;
                request.ServicePoint.Expect100Continue = false;
                byte[] bytes = Encoding.Default.GetBytes(cmd);
                request.ContentLength = bytes.Length;
                Stream requestStream = request.GetRequestStream();
                requestStream.Write(bytes, 0, bytes.Length);
                requestStream.Close();
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                while ((str = reader.ReadLine()) != null)
                {
                    str2 = str2 + str;
                }
            }
            catch
            {

            }
            try
            {
                //DateTime dt = DateTime.Now;
                //GVar.directorypath = "D:\\BZTemp\\";
                //if (!Directory.Exists(GVar.directorypath))
                //{
                //    Directory.CreateDirectory(GVar.directorypath);
                //}
                //string fileName = dt.ToString("yyyy-MM-dd") + ".txt";
                //GVar.filepath = GVar.directorypath + fileName;
                //if (!File.Exists(GVar.filepath))
                //{
                //    File.Create(GVar.filepath).Close();
                //}
                //FileStream fs = new FileStream(GVar.filepath, FileMode.Append, FileAccess.Write);
                //StreamWriter sw = new StreamWriter(fs, Encoding.Default);
                //sw.WriteLine(dt.ToString("yyyy-MM-dd") + "   " + dt.ToString("HH:mm:ss") + "   " + "发送的数据为：" + cmd);
                //sw.WriteLine(dt.ToString("yyyy-MM-dd") + "   " + dt.ToString("HH:mm:ss") + "   " + "接收到返回的数据为：：" + str2);
                //sw.Flush();
                //sw.Close();
                //fs.Close();
            }
            catch
            {
                //UpdateInfo("异常信息保存失败！", 1);
            }
        }
    }
}
